<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Model;
use think\Request;
use think\Response;

class Status extends BaseController
{
    protected Model $model;
    public function initialize(): void
    {
        $this->model = new \app\model\Status();
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $team_id = $request->get('enterprise_id',0);
        if(!$team_id){
            $this->result(403,'无法获取企业ID，请重新登录或是选择企业');
        }
        try {
            $result = $this->model->where('enterprise_id', $team_id)->select();
            return $this->result(200,'获取成功',$result);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->result($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $data = $request->post();
        try {
            $this->validate($data,'Status');
            if($this->model->where('name',$data['name'])
                ->where('team_id',$data['team_id'])->find()){
                return apiResponse(403,'状态名重复');
            }
            $result = $this->model->createStatus($data);
            return apiResponse($result['code'], $result['message']);
        }catch (ValidateException $e){
            return apiResponse(400,$e->getMessage());
        }
    }
    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param  int  $id
     * @return void
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete(int $id): Response
    {
        $this->model->destroy($id);
        return apiResponse(200,'删除成功');
    }
}
